package club.janna.jrpc.remoting.netty;

import club.janna.jrpc.remoting.Codec;
import club.janna.jrpc.remoting.Handler;
import club.janna.jrpc.remoting.Server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.URI;

/**
 * @author Panbo.Guo
 */
@Slf4j
public class NettyServer implements Server {
    @Override
    public void start(URI uri, Codec codec, Handler serverHandler) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        /**
                         * Frame Decoder
                         * BEFORE DECODE                                     AFTER DECODE
                         * +----------+--------------+----------------+      +----------------+
                         * | Header 1 |  Length      | Actual Content |----->| Actual Content |
                         * |  0xCAFE  | 0x0000000C   | "HELLO, WORLD" |      | "HELLO, WORLD" |
                         * +----------+------------ -+----------------+      +----------------+
                         */
                        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(10240,
                                2, 4, 0, 6));
                        channel.pipeline().addLast(new FrameEncoder());
                        channel.pipeline().addLast(new NettyCodec(codec));
                        channel.pipeline().addLast(new NettyServerHandler(serverHandler));
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(new InetSocketAddress(uri.getHost(), uri.getPort())).sync();
            log.info("Server started on {}:{}", uri.getHost(), uri.getPort());
            // future.channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
